package edu.wust.cs.cm;

import android.app.ListActivity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

//查找Contact界面
public class ContactSearcher extends ListActivity {
	
	 public static final String TAG = "ContactSearcher";
	 
	 public static final String [] searchTypeNames = {"Name", "Phone", "Email", "IM"};
	 
	 private EditText searchEditText;
	 
	 private Spinner searchTypeSpinner;
	 
    /**
     * Called when the activity is first created. Responsible for initializing the UI.
     */
	@Override
	//界面最先调用的入口函数
	protected void onCreate(Bundle savedInstanceState) {
		Log.v(TAG, "Activity State: onCreate()");
		super.onCreate(savedInstanceState);
		
		//Use a custom search layout
		setContentView(R.layout.contact_searcher);
		
		// Obtain handles to UI objects
		this.searchEditText = (EditText) findViewById(R.id.searcherEditText);
		this.searchTypeSpinner = (Spinner) findViewById(R.id.searcherSpinner);
		
		ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, 
															android.R.layout.simple_spinner_item,
															searchTypeNames);
		arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		this.searchTypeSpinner.setAdapter(arrayAdapter);
		this.searchTypeSpinner.setPrompt(getString(R.string.searchTypeLabel));
		
		// Register handlers for UI elements
		//当查找关键字变化的时就动态的查找，即添加Text change 事件的响应函数
		//就是但关键字变化时就会被这个Listener监听到，从而实现动态的搜索
		this.searchEditText.addTextChangedListener(new TextWatcher(){

			@Override
			public void afterTextChanged(Editable s) {
				//Search the contact
				String keyword = s.toString();
				String type = searchTypeNames[searchTypeSpinner.getSelectedItemPosition()];
				Log.i(TAG, "search contact by : " + keyword + " & " + type);
				//根据关键字和类型来查找，得到符合的Contact集合
				Cursor cursor = searchContact(keyword, type);
				//刷新显示新的Contact集合
				populateContactList(cursor);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// Do nothing
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				//Do nothing
			}
		});
		//默认的使用空名字和名字类型来查找
		Cursor cursor = searchContact("", searchTypeNames[0]);
		populateContactList(cursor);
		
	}
	
	/**
     * Populate the contact list based on account currently selected in the account spinner.
     */
	//刷新显示新的Contact集合
    private void populateContactList(Cursor cursor) {
        // Build adapter with contact entries
    	ContactListItemAdapter adapter = new ContactListItemAdapter(this, R.layout.contact_manager, cursor);
        startManagingCursor(cursor);
        setListAdapter(adapter);
        getListView().setTextFilterEnabled(true);
    }
    
	/**
	 * search contact by the keywords and type.
	 * @param keyword
	 * @param type
	 * @return Cursor of contacts. 
	 */
    //关键的Search Contact 函数
	protected Cursor searchContact(String keyword, String type) {
        Uri uri =  ContactsContract.Data.CONTENT_URI;
        String[] projection = ContactListItemAdapter.CONTACTS_SUMMARY_PROJECTION;
        String selection = null;
        String[] selectionArgs = null;
        
        //根据关键字的类型来构造不同的查找方式
        if (type.equals(searchTypeNames[0])) {//按名字关键字查找
        	uri = Contacts.CONTENT_URI;
        	selection = Contacts.DISPLAY_NAME + " like '%" + keyword + "%'";
        }
        else if (type.equals(searchTypeNames[1])) {//按Phone number关键字查找
        	selection = ContactsContract.Data.DATA1 + " like '" + keyword + "%' AND "
        					+ ContactsContract.Data.MIMETYPE + " = '" 
        					+ ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'";
        }
        else if (type.equals(searchTypeNames[2])) {//按Email关键字查找
        	selection = ContactsContract.Data.DATA1 + " like '%" + keyword + "%' AND "
							+ ContactsContract.Data.MIMETYPE + " = '" 
							+ ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE + "'";
        }
        else if (type.equals(searchTypeNames[3])) {//按IM关键字查找
        	selection = ContactsContract.Data.DATA1 + " like '" + keyword + "%' AND "
        					+ ContactsContract.Data.MIMETYPE + " = '" 
        					+  ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE + "'";
        }
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
        //执行查找
		return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
	}
}
